package com.hcinfos.gsoo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.services.poisearch.PoiResult;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.easemob.chat.ConnectionListener;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chatuidemo.db.DbOpenHelper;
import com.easemob.chatuidemo.db.UserDao;
import com.easemob.chatuidemo.domain.User;
import com.easemob.chatuidemo.utils.PreferenceUtils;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.enity.City;
import com.hcinfos.gsoo.enity.GdMealsDish;
import com.hcinfos.gsoo.enity.GroupByInfo;
import com.hcinfos.gsoo.enity.ViewSuppSearchExt;
import com.hcinfos.gsoo.service.LocationService;
import com.hcinfos.gsoo.util.LogUtil;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

public class GsooApplication extends Application {

	private static GsooApplication mInstance = null;
	public boolean m_bKeyRight = true;
	public BMapManager mBMapManager = null;
	public static final String strKey = "300D2EA1C02F7A7E10E741D872BF31F94216A826";

	public static List<Bitmap> uploadImgs;
	public static GeoPoint currentLocation;
	public static Map<String, Bitmap> cacheIcons = new HashMap<String, Bitmap>();
	public static final Map<String, String> cacaheMap = new HashMap<String, String>();

	
	
	public static String ggNumber = null;
	public static String password = null;
	public static Double lat = null;
	public static Double lng = null;
	public static String address = null;
	public static String cityName = null;
	public static String cityCode = null;
	public static boolean isSameCity = true;
	public static City currentCity = null;// 当前城市 也是上一次选择的城市

	public static List<GroupByInfo> cacheGroupList = null;
	public static List<ViewSuppSearchExt> cacheSupExtList = null;
	public static int currentPage = 0;
	public static PoiResult poiResult = null;
	public static ViewSuppSearchExt tempSuppExt = null;// 临时存放 一键采集的数据

	public static SlidingMenu sildingMenu = null;
	public static boolean isShowTipChangeCity = true;// 显示提示切换城市

	public LocationClient mLocationClient;
	public MyLocationListener mMyLocationListener;
	private boolean isLocation = true;

	public static Map<String, GdMealsDish> menuMap = new HashMap<String, GdMealsDish>();
	public static Context applicationContext;
	// login user name
	public final String PREF_USERNAME = "username";
	// login password
	private static final String PREF_PWD = "pwd";
	private String userName = null;
	private Map<String, User> contactList;
	/**
	 * 当前用户nickname,为了苹果推送不是userid而是昵称
	 */
	public static String currentUserNick = "";
	@Override
	public void onCreate() {
		Log.d("wxf", "application onCreate");
		applicationContext = this;
//		 CrashHandler crashHandler = CrashHandler.getInstance();
//		
//		 crashHandler.init(getApplicationContext());
		
		mLocationClient = new LocationClient(this.getApplicationContext());
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式
		option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);// 返回的定位结果包含地址信息
		option.setNeedDeviceDirect(true);// 返回的定位结果包含手机机头的方向
		mLocationClient.setLocOption(option);
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
		mInstance = this;
		initEngineManager(this);
		initChat();
		super.onCreate();
	}

	public static void reset() {
		poiResult = null;
		currentPage = 0;
		tempSuppExt = null;
	}

	public void initEngineManager(Context context) {
		if (mBMapManager == null) {
			mBMapManager = new BMapManager(context);
		}
		if (!mBMapManager.init(strKey, new MyGeneralListener())) {
//			Toast.makeText(
//					GsooApplication.getInstance().getApplicationContext(),
//					"BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
		}
	}

	public static GsooApplication getInstance() {
		return mInstance;
	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	public static class MyGeneralListener implements MKGeneralListener {

		@Override
		public void onGetNetworkState(int iError) {
			if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
				Toast.makeText(
						GsooApplication.getInstance().getApplicationContext(),
						"您的网络出错啦！", Toast.LENGTH_LONG).show();
			} else if (iError == MKEvent.ERROR_NETWORK_DATA) {

			}
		}

		@Override
		public void onGetPermissionState(int iError) {
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
				// 授权Key错误：
				// Toast.makeText(
				// GsooApplication.getInstance().getApplicationContext(),
				// "请在 GsooApplication.java文件输入正确的授权Key！",
				// Toast.LENGTH_LONG).show();
				GsooApplication.getInstance().m_bKeyRight = false;
			}
		}
	}

	/**
	 * 实现实位回调监听
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// Receive Location
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			GsooApplication.lat = location.getLatitude();
			GsooApplication.lng = location.getLongitude();
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\ndirection : ");
				sb.append("\naddr : ");
				sb.append(location.getAddrStr() + ",cityName="
						+ location.getCity());
				sb.append(location.getDirection());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				// 运营商信息
				sb.append("\noperationers : " + location.getAddrStr()
						+ ",cityName=" + location.getCity());
				sb.append(location.getOperators());
				GsooApplication.address = location.getAddrStr();
				GsooApplication.cityName = location.getCity();
			}
			Intent intent = new Intent(LocationService.LOCATION_ACTION);
			sendBroadcast(intent);
			mLocationClient.stop();
			LogUtil.d("wxf", "location=" + sb.toString());
		}

	}

	/**
	 * IM
	 */
	private void initChat() {
		EMChat.getInstance().init(applicationContext);
		EMChat.getInstance().setDebugMode(true);
		Log.d("EMChat Demo", "initialize EMChat SDK");

		// 获取到EMChatOptions对象
		EMChatOptions options = EMChatManager.getInstance().getChatOptions();
		// 默认添加好友时，是不需要验证的，改成需要验证
		options.setAcceptInvitationAlways(false);
		// 设置收到消息是否有新消息通知，默认为true
		options.setNotifyBySoundAndVibrate(PreferenceUtils.getInstance(
				applicationContext).getSettingMsgNotification());
		// 设置收到消息是否有声音提示，默认为true
		options.setNoticeBySound(PreferenceUtils
				.getInstance(applicationContext).getSettingMsgSound());
		// 设置收到消息是否震动 默认为true
		options.setNoticedByVibrate(PreferenceUtils.getInstance(
				applicationContext).getSettingMsgVibrate());
		// 设置语音消息播放是否设置为扬声器播放 默认为true
		options.setUseSpeaker(PreferenceUtils.getInstance(applicationContext)
				.getSettingMsgSpeaker());

		// 设置notification消息点击时，跳转的intent为自定义的intent
		// options.setOnNotificationClickListener(new
		// OnNotificationClickListener() {
		//
		// @Override
		// public Intent onNotificationClick(EMMessage message) {
		// Intent intent = new Intent(applicationContext, ChatActivity.class);
		// ChatType chatType = message.getChatType();
		// if (chatType == ChatType.Chat) { // 单聊信息
		// intent.putExtra("userId", message.getFrom());
		// intent.putExtra("chatType", ChatActivity.CHATTYPE_SINGLE);
		// } else { // 群聊信息
		// // message.getTo()为群聊id
		// intent.putExtra("groupId", message.getTo());
		// intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
		// }
		// return intent;
		// }
		// });
	}

	class MyConnectionListener implements ConnectionListener {
		@Override
		public void onReConnecting() {
		}

		@Override
		public void onReConnected() {
		}

		@Override
		public void onDisConnected(String errorString) {
			// if (errorString != null && errorString.contains("conflict")) {
			// Intent intent = new Intent(applicationContext,
			// MainActivity.class);
			// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			// intent.putExtra("conflict", true);
			// startActivity(intent);
			// }

		}

		@Override
		public void onConnecting(String progress) {

		}

		@Override
		public void onConnected() {
		}
	}

	/**
	 * 获取当前登陆用户名
	 * 
	 * @return
	 */
	public String getUserName() {
		if (userName == null) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			userName = preferences.getString(PREF_USERNAME, null);
		}
		return userName;
	}

	/**
	 * 获取密码
	 * 
	 * @return
	 */
	public String getPassword() {
		if (password == null) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			password = preferences.getString(PREF_PWD, null);
		}
		return password;
	}

	/**
	 * 设置用户名
	 * 
	 * @param user
	 */
	public void setUserName(String username) {
		if (username != null) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			SharedPreferences.Editor editor = preferences.edit();
			if (editor.putString(PREF_USERNAME, username).commit()) {
				userName = username;
			}
		}
	}

	/**
	 * 设置密码 下面的实例代码 只是demo，实际的应用中需要加password 加密后存入 preference 环信sdk
	 * 内部的自动登录需要的密码，已经加密存储了
	 * 
	 * @param pwd
	 */
	public void setPassword(String pwd) {
		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(applicationContext);
		SharedPreferences.Editor editor = preferences.edit();
		if (editor.putString(PREF_PWD, pwd).commit()) {
			password = pwd;
		}
	}

	/**
	 * 获取内存中好友user list
	 * 
	 * @return
	 */
	public Map<String, User> getContactList() {
		if (getUserName() != null) {
			UserDao dao = new UserDao(applicationContext);
			// 获取本地好友user list到内存,方便以后获取好友list
			contactList = dao.getContactList();
		}
		return contactList;
	}
	/**
	 * 退出登录,清空数据
	 */
	public void logout() {
		// 先调用sdk logout，在清理app中自己的数据
		EMChatManager.getInstance().logout();
		DbOpenHelper.getInstance(applicationContext).closeDB();
		// reset password to null
		setPassword(null);
		setContactList(null);

	}
	/**
	 * 设置好友user list到内存中
	 * 
	 * @param contactList
	 */
	public void setContactList(Map<String, User> contactList) {
		this.contactList = contactList;
	}
}
